package com.cloud.rocketmqtxconsumer.config;

import com.cloud.rocketmqtxconsumer.listener.OrderMessageListener;
import com.cloud.rocketmqtxconsumer.service.PayService;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
@SuppressWarnings("all")
public class RocketConsumerConfig {

    private static final String CONSUMER_GROUP = "consumer_transaction_group";
    private static final String NAME_SERVER_ADDRESS="192.168.142.142:9876";
    private static final String MESSAGE_TOPIC="transaction_topic_order";

    private DefaultMQPushConsumer consumer;

    @Autowired
    @Qualifier("messageListener")
    private OrderMessageListener messageListener;

    @PostConstruct
    public void init() throws MQClientException {
        //初始化消费者
        consumer = new DefaultMQPushConsumer(CONSUMER_GROUP);
        //设置消息的消费方式，为：集群模式，集群模式下，同一个组中，一条消息只有一个消费者消费
        consumer.setMessageModel(MessageModel.CLUSTERING);
        //设置 nameServer的地址
        consumer.setNamesrvAddr(NAME_SERVER_ADDRESS);
        //设置监听的主题，以及过滤条件
        consumer.subscribe(MESSAGE_TOPIC,"*");
        //添加消息梳理监听
        consumer.registerMessageListener(messageListener);

        // 2次失败 就进死信队列，后面还要对死信队列进行处理
        consumer.setMaxReconsumeTimes(2);
        consumer.start();
    }
}
